package com.csdj.user.ws;

import com.csdj.user.vo.WsData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Component
@ServerEndpoint("/ws/chat")
public class WebSocketTest {

    private Logger log = LoggerFactory.getLogger("websocket");

    private ObjectMapper om = new ObjectMapper();

    private static Set<Session> sessions = new HashSet<>();

    /**
     * 当客户端创建连接后执行的方法
     * @param session
     */
    @OnOpen
    public void onConnection(Session session){
        log.info("id:{}建立连接",session.getId());
        final WsData wsData = new WsData();
        wsData.setCmd("welcome");
        wsData.setName("system");
        wsData.setContent("欢迎光临");
        try {
            send(session,wsData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭执行的方法
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        log.info("id:{}关闭连接",session.getId());
        sessions.remove(session);
    }

    /**
     * 异常执行方法
     * @param e
     */
    @OnError
    public void onError(Throwable e){
        e.printStackTrace();
    }

    /**
     * 接受客户端发过来的消息
     * @param msg
     * @param session
     */
    @OnMessage
    public void onMsg(String msg, Session session){
        try {
            WsData data = om.readValue(msg,WsData.class);
            if(data != null){
                switch (data.getCmd()){
                    case "login":{
                        sessions.add(session);
                        final WsData wsData = new WsData();
                        wsData.setCmd("chat");
                        wsData.setName("system");
                        wsData.setContent(data.getName()+"加入了聊天室");
                        sendAll(wsData);
                        break;
                    }
                    case "chat":{
                        //把收到的聊天内容发送到所有用户
                        sendAll(data);
                        break;
                    }
                }
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        log.info("收到{}:{}",session.getId(),msg);
    }

    /**
     * 发送消息
     * @param session
     * @param msg
     */
    public void send(Session session,WsData msg){
        if(session.isOpen()){
            try {
                session.getBasicRemote().sendText(om.writeValueAsString(msg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给所有登录用户发送消息
     * @param msg
     */
    public void sendAll(WsData msg){
        sessions.parallelStream().forEach(s ->{
            send(s,msg);
        });
    }
}
